/**
 * @file UserManagement.jsx
 * @description 后台管理系统的用户管理页面组件
 */
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { 
  Table, Card, Typography, Space, Button, Tag, Modal, 
  Form, Select, Input, Drawer, Descriptions, Divider, message, App as AntdAppHook // 导入 App
} from 'antd';
import { 
  ReloadOutlined, SearchOutlined, EyeOutlined, 
  EditOutlined, UserAddOutlined, DeleteOutlined 
} from '@ant-design/icons';
import { fetchAllUsers, updateUserRole, addAdminUser, deleteAdminUser } from '../store/usersSlice';
import toast from 'react-hot-toast';

const { Title } = Typography;
const { Option } = Select;

const UserManagement = () => {
  const dispatch = useDispatch();
  const { users, roles, isLoading } = useSelector((state) => state.users);
  const [filteredUsers, setFilteredUsers] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [viewUser, setViewUser] = useState(null);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [updateForm] = Form.useForm();
  const [addForm] = Form.useForm();
  const { modal } = AntdAppHook.useApp(); // 获取 modal 实例

  useEffect(() => {
    dispatch(fetchAllUsers());
  }, [dispatch]);

  useEffect(() => {
    if (users.length > 0) {
      let filtered = [...users];
      
      if (searchText) {
        filtered = filtered.filter(user => 
          (user.name && user.name.toLowerCase().includes(searchText.toLowerCase())) ||
          (user.email && user.email.toLowerCase().includes(searchText.toLowerCase())) ||
          (user.username && user.username.toLowerCase().includes(searchText.toLowerCase()))
        );
      }
      
      setFilteredUsers(filtered);
    } else {
      setFilteredUsers([]);
    }
  }, [users, searchText]);

  const handleSearch = (value) => {
    setSearchText(value);
  };

  const handleRefresh = () => {
    dispatch(fetchAllUsers());
    toast.success('用户数据已刷新');
  };

  const showUserDetails = (user) => {
    setViewUser(user);
    setDrawerVisible(true);
  };

  const closeDrawer = () => {
    setDrawerVisible(false);
  };

  const showUpdateModal = (user) => {
    setCurrentUser(user);
    updateForm.setFieldsValue({ roleId: user.roleId || null });
    setUpdateModalVisible(true);
  };

  const handleUpdateCancel = () => {
    setUpdateModalVisible(false);
    setCurrentUser(null);
    updateForm.resetFields();
  };

  const handleUpdateSubmit = async () => {
    try {
      const values = await updateForm.validateFields();
      dispatch(updateUserRole({ userId: currentUser.id, roleId: values.roleId }));
      toast.success(`用户 ${currentUser.name || currentUser.username} 角色已更新`);
      setUpdateModalVisible(false);
      setCurrentUser(null);
      updateForm.resetFields();
    } catch (error) {
      console.error('表单验证或更新失败:', error);
    }
  };

  const showAddModal = () => {
    setAddModalVisible(true);
  };

  const handleAddCancel = () => {
    setAddModalVisible(false);
    addForm.resetFields();
  };

  const handleAddSubmit = async () => {
    try {
      const values = await addForm.validateFields();
      
      const usernameExists = users.some(user => user.username === values.username);
      if (usernameExists) {
        toast.error('用户名已存在，请使用其他用户名');
        return;
      }
      
      const newUser = {
        id: Date.now(), 
        username: values.username,
        password: values.password,
        name: values.name,
        email: values.email,
        roleId: values.roleId,
        createdAt: new Date().toISOString(),
      };
      
      dispatch(addAdminUser(newUser));
      toast.success(`管理员用户 ${values.name} 已创建`);
      setAddModalVisible(false);
      addForm.resetFields();
    } catch (error) {
      console.error('表单验证或添加失败:', error);
    }
  };

  const handleDeleteUser = (user) => {
    console.log('Attempting to delete user:', user); 
    modal.confirm({ // 使用从 hook 获取的 modal 实例
      title: '确认删除',
      content: `确定要删除用户 ${user.name || user.username} 吗？此操作不可撤销。`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        dispatch(deleteAdminUser(user.id));
        toast.success(`用户 ${user.name || user.username} 已删除`);
      },
    });
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '角色',
      dataIndex: 'roleId',
      key: 'roleId',
      render: (roleId) => {
        const role = roles.find(r => r.id === roleId);
        return role ? (
          <Tag color="blue">{role.name}</Tag>
        ) : '未分配';
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => date ? new Date(date).toLocaleDateString('zh-CN') : '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => showUserDetails(record)}
          >
            查看
          </Button>
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => showUpdateModal(record)}
          >
            分配角色
          </Button>
          <Button 
            type="text" 
            danger
            icon={<DeleteOutlined />} 
            onClick={() => handleDeleteUser(record)}
            disabled={record.username === 'admin'}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Title level={2}>用户管理</Title>
      
      <Card style={{ marginBottom: 16 }}>
        <Space style={{ marginBottom: 16 }}>
          <Input.Search
            placeholder="搜索用户名或邮箱"
            allowClear
            onSearch={handleSearch}
            style={{ width: 250 }}
          />
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
          >
            刷新
          </Button>
          <Button 
            type="primary" 
            icon={<UserAddOutlined />} 
            onClick={showAddModal}
          >
            添加管理员
          </Button>
        </Space>
        
        <Table 
          columns={columns} 
          dataSource={filteredUsers.map(user => ({ ...user, key: user.id }))} 
          loading={isLoading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Drawer
        title="用户详情"
        placement="right"
        width={500}
        onClose={closeDrawer}
        open={drawerVisible}
      >
        {viewUser && (
          <>
            <Descriptions bordered column={1}>
              <Descriptions.Item label="用户ID">{viewUser.id}</Descriptions.Item>
              <Descriptions.Item label="用户名">{viewUser.username || '-'}</Descriptions.Item>
              <Descriptions.Item label="姓名">{viewUser.name}</Descriptions.Item>
              <Descriptions.Item label="邮箱">{viewUser.email}</Descriptions.Item>
              <Descriptions.Item label="角色">
                {(() => {
                  const role = roles.find(r => r.id === viewUser.roleId);
                  return role ? <Tag color="blue">{role.name}</Tag> : '未分配';
                })()}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {viewUser.createdAt ? new Date(viewUser.createdAt).toLocaleString('zh-CN') : '-'}
              </Descriptions.Item>
            </Descriptions>

            {viewUser.roleId && (
              <>
                <Divider orientation="left">权限信息</Divider>
                <Descriptions bordered column={1}>
                  <Descriptions.Item label="权限列表">
                    {(() => {
                      const role = roles.find(r => r.id === viewUser.roleId);
                      if (role) {
                        return role.permissions.map(perm => (
                          <Tag key={perm} color="green" style={{ margin: '2px' }}>
                            {perm === 'all' ? '所有权限' : 
                             perm === 'orders' ? '订单管理' :
                             perm === 'users' ? '用户管理' :
                             perm === 'roles' ? '角色管理' :
                             perm === 'products' ? '商品管理' :
                             perm === 'view_users' ? '查看用户' : perm}
                          </Tag>
                        ));
                      }
                      return '无权限';
                    })()}
                  </Descriptions.Item>
                </Descriptions>
              </>
            )}
          </>
        )}
      </Drawer>

      <Modal
        title="分配用户角色"
        open={updateModalVisible}
        onCancel={handleUpdateCancel}
        footer={[
          <Button key="cancel" onClick={handleUpdateCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleUpdateSubmit}>
            确认更新
          </Button>,
        ]}
      >
        {currentUser && (
          <Form form={updateForm} layout="vertical">
            <Form.Item
              name="roleId"
              label="用户角色"
              rules={[{ required: true, message: '请选择用户角色' }]}
            >
              <Select placeholder="请选择角色">
                {roles.map(role => (
                  <Option key={role.id} value={role.id}>{role.name}</Option>
                ))}
              </Select>
            </Form.Item>
            <p>用户: {currentUser.name || currentUser.username}</p>
            <p>邮箱: {currentUser.email}</p>
          </Form>
        )}
      </Modal>

      <Modal
        title="添加管理员用户"
        open={addModalVisible}
        onCancel={handleAddCancel}
        footer={[
          <Button key="cancel" onClick={handleAddCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleAddSubmit}>
            创建用户
          </Button>,
        ]}
      >
        <Form form={addForm} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[{ required: true, message: '请输入邮箱' }, { type: 'email', message: '请输入有效的邮箱地址' }]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="roleId"
            label="用户角色"
            rules={[{ required: true, message: '请选择用户角色' }]}
          >
            <Select placeholder="请选择角色">
              {roles.map(role => (
                <Option key={role.id} value={role.id}>{role.name}</Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;